package com.caius.xiaohashu.count.biz.consumer;

import com.caius.framework.common.util.JsonUtils;
import com.caius.xiaohashu.count.biz.constant.MQConstants;
import com.caius.xiaohashu.count.biz.constant.RedisKeyConstants;
import com.caius.xiaohashu.count.biz.domain.mapper.UserCountDOMapper;
import com.caius.xiaohashu.count.biz.model.dto.NoteOperateMqDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author Caius
 * @description
 * @since Created in 2025-05-28
 */
@Component
@RocketMQMessageListener(consumerGroup = "xiaohashu_group_" + MQConstants.TOPIC_NOTE_OPERATE,
        topic = MQConstants.TOPIC_NOTE_OPERATE
)
@Slf4j
public class CountNotePublishConsumer implements RocketMQListener<Message> {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserCountDOMapper userCountDOMapper;

    @Override
    public void onMessage(Message message) {
        String bodyJsonStr = new String(message.getBody());

        String tags = message.getTags();

        if (Objects.equals(tags, MQConstants.TAG_NOTE_PUBLISH)) {
            handleNoteTagMessage(bodyJsonStr, 1);
        } else if (Objects.equals(tags, MQConstants.TAG_NOTE_DELETE)) {
            handleNoteTagMessage(bodyJsonStr, -1);
        }
    }

    /**
     * 发布,删除笔记
     * @param bodyJsonStr
     */
    private void handleNoteTagMessage(String bodyJsonStr, long count) {
        NoteOperateMqDTO noteOperateMqDTO = JsonUtils.parseObject(bodyJsonStr, NoteOperateMqDTO.class);
        if (Objects.isNull(noteOperateMqDTO)) return ;

        Long creatorId = noteOperateMqDTO.getCreatorId();

        String countUserKey = RedisKeyConstants.buildCountUserKey(creatorId);

        Boolean isExists = redisTemplate.hasKey(countUserKey);

        if (isExists) {
            redisTemplate.opsForHash().increment(countUserKey, RedisKeyConstants.FIELD_NOTE_TOTAL, count);
        }

        userCountDOMapper.insertOrUpdateNoteTotalByUserId(count, creatorId);
    }
}
